<?php

namespace App\Filament\Widgets;

use App\Models\BorrowRecord;
use Carbon\Carbon;
use Filament\Widgets\StatsOverviewWidget as BaseWidget;
use Filament\Widgets\StatsOverviewWidget\Stat;

class BorrowRecordOverview extends BaseWidget
{
    protected function getStats(): array
    {
        // 获取当前日期
        $today = Carbon::now();

        // 获取过去七天的日期范围
        $lastSevenDays = Carbon::now()->subMonths();

        // 查询最近七天每天的借阅量
        $result = BorrowRecord::selectRaw('DATE(updated_at) as date, COUNT(*) as borrow_count')
            ->whereBetween('updated_at', [$lastSevenDays, $today])
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->pluck('borrow_count');

        $borrow = BorrowRecord::selectRaw('DATE(updated_at) as date, COUNT(*) as borrow_count')
            ->whereBetween('updated_at', [$lastSevenDays, $today])
            ->where('returned',0)
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->pluck('borrow_count');

        $returned = BorrowRecord::selectRaw('DATE(updated_at) as date, COUNT(*) as borrow_count')
            ->whereBetween('updated_at', [$lastSevenDays, $today])
            ->where('returned',1)
            ->groupBy('date')
            ->orderBy('date', 'asc')
            ->pluck('borrow_count');

        return [
            //
//            Stat::make('总借阅', BorrowRecord::count())
//                ->chart($result->toArray())
//                ->description('用户总借阅数量')
//                ->descriptionIcon('heroicon-o-book-open')
//                ->color('primary'),
            Stat::make('申请', BorrowRecord::where('returned',3)->count())
                ->chart($returned->toArray())
                ->description('待审核借阅数量')
                ->color('info'),
            Stat::make('借出', BorrowRecord::where('returned',0)->count())
                ->chart($borrow->toArray())
                ->description('用户借阅中数量')
                ->color('warning'),
            Stat::make('归还', BorrowRecord::where('returned',1)->count())
                ->chart($returned->toArray())
                ->description('用户归还数量')
                ->color('success'),

            Stat::make('逾期', BorrowRecord::where('returned',2)->count())
                ->chart($returned->toArray())
                ->description('已经逾期未归还书籍数量')
                ->color('danger'),
        ];
    }
}
